// ui/components/TagInput.js
// Assuming ElementPlus components (ElSelect, ElOption) are globally available.

export default {
  name: 'TagInput',
  props: {
    modelValue: { // For v-model
      type: Array, // Was Array as PropType<string[]>
      required: true,
      default: () => []
    },
    availableTags: {
      type: Array, // Was Array as PropType<string[]>
      required: false,
      default: () => []
    },
    placeholder: {
      type: String,
      default: '添加或选择标签...'
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const { ref, watch } = Vue; // Vue is global

    const selectedTagsRef = ref([...props.modelValue]);

    watch(() => props.modelValue, (newValue) => {
      // Basic check to prevent infinite loops if objects are identical
      if (JSON.stringify(newValue) !== JSON.stringify(selectedTagsRef.value)) {
        selectedTagsRef.value = [...newValue];
      }
    }, { deep: true });

    function handleSelectionChange(newSelectedValues) { // newSelectedValues was string[]
      const normalizedValues = newSelectedValues.map(tag => String(tag).trim()).filter(tag => tag.length > 0);
      
      if (JSON.stringify(normalizedValues) !== JSON.stringify(props.modelValue)) {
        emit('update:modelValue', normalizedValues);
      }
      // Update local ref if normalization changed the array instance or content
      if (JSON.stringify(normalizedValues) !== JSON.stringify(selectedTagsRef.value)) {
         selectedTagsRef.value = normalizedValues;
      }
    }

    return {
      props, // Make props available in template if needed directly (though usually accessed via context)
      selectedTagsRef,
      handleSelectionChange,
    };
  },
  template: `
  <el-select
    v-model="selectedTagsRef"
    multiple
    filterable
    allow-create
    default-first-option
    :placeholder="props.placeholder || '添加或选择标签...'"
    class="tag-input-select"
    @change="handleSelectionChange"
    :automatic-dropdown="true"
    fit-input-width
  >
    <el-option
      v-for="item in props.availableTags"
      :key="item"
      :label="String(item)"
      :value="String(item)"
    />
  </el-select>
  `
};